package br.com.news.activity;

import java.util.List;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import br.com.news.R;
import br.com.news.exception.ServiceException;
import br.com.news.modal.CategoriaBean;
import br.com.news.service.interfaces.ICategoriaService;
import br.com.news.util.Constantes;
import br.com.news.util.DialogUtil;
import br.com.news.util.DialogUtil.ButtonDialog;

/**
 * Adapter da lista de categorias
 * 
 * @author Jefferson
 * @since 19/03/2013
 */
public class CategoriaAdapter extends BaseAdapter {
	
	private Context context;
	private List<CategoriaBean> categoriaBeans;
	private ICategoriaService categoriaService;

	public CategoriaAdapter(Context context, List<CategoriaBean> categoriaBeans, ICategoriaService categoriaService) {
		this.context = context;
		this.categoriaBeans = categoriaBeans;
		this.categoriaService = categoriaService;
	}
	
	@Override
	public int getCount() {
		return categoriaBeans.size();
	}

	@Override
	public Object getItem(int position) {
		return categoriaBeans.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View view, ViewGroup viewGroup) {
		
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		CheckBox checkBox = (CheckBox) inflater.inflate(R.layout.activity_categoria_item, null);
		
		final CategoriaBean categoriaBean = categoriaBeans.get(position);
		
		checkBox.setText(categoriaBean.getDescricao());
		checkBox.setChecked(categoriaBean.isSelecionada());
		
		checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				categoriaBean.setSelecionada(isChecked);
				try {
					categoriaService.atualizar(categoriaBean);
				} catch (ServiceException e) {
					Log.e(Constantes.LOG, e.getMessage(), e);
					DialogUtil.showDialog(context, context.getString(R.string.falha_selecionar_categoria), ButtonDialog.getButtonOk(context));
				}
			}
		});
		
		return checkBox;
	}

}
